#pragma once
#include <string>
#include <unordered_map>
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include "log.hpp"
#include "inetAddr.hpp"

using namespace LogModule;

const char* defaultPath = "./dictionary.txt";
const std::string sep = ": ";

class Dict
{
public:
    Dict(std::string path = defaultPath)
        :_path(path)
    {}

    bool Load()
    {
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG((int)LogLevel::ERROR) << "文件打开失败！";
            return false;
        }
        std::string line;
        while (getline(in, line))
        {
            
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG((int)LogLevel::WARNING) << "单词格式错误！";
                continue;
            }
            std::string chinese = line.substr(0, pos);
            std::string english = line.substr(pos + sep.size());
            _words[chinese] = english;
            if (english.empty() || chinese.empty())
            {
                LOG((int)LogLevel::WARNING) << "没有有效内容: " << line;
                continue;
            }
            LOG((int)LogLevel::DEBUG) << "加载: " << line;
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _words.find(word);
        if (iter == _words.end())
        {
            LOG((int)LogLevel::DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->None";
            return "None";
        }
        LOG((int)LogLevel::DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->" << iter->second;
        return iter->second;
    }
private:
    std::unordered_map<std::string, std::string> _words;
    std::string _path;
};